package com.xiaotu.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class FileUtil
{
    private static final Logger LOGGER = LoggerFactory
            .getLogger(FileUtil.class);

    private static final String CACHE_PATH = "file.cache.path";

    public static void writeFile(String fileName, String content)
    {
        OutputStreamWriter osw = null;
        try
        {
            File path = new File(fileName).getParentFile();
            if (!path.exists())
                path.mkdirs();

            osw = new OutputStreamWriter(new FileOutputStream(fileName, true),
                    PropertiesUtil.getProperty(
                            Constants.SpiderConfigKey.FILE_ENCODE));
            osw.write(content);

        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            try
            {
                osw.flush();
                osw.close();
            }
            catch (IOException e)
            {
                LOGGER.error(StringUtils.EMPTY, e);
            }

        }
    }

    public static final String getCacheFilePath(String fileName)
    {
        return PropertiesUtil.getProperty(CACHE_PATH) + fileName;
    }

    /**
     * 去掉文件扩展名
     *
     * @param fileName
     * @return
     */
    public static String removeExtendName(String fileName, String extName)
    {
        if (StringUtil.isEmpty(fileName) || StringUtil.isEmpty(extName))
        {
            return fileName;
        }
        if (fileName.endsWith(extName))
            return fileName.substring(0, fileName.indexOf(extName));
        return fileName;
    }

    /**
     * 获取文件名（不包含扩展名）
     *
     * @param fileName
     * @return
     */
    public static String getFileNameWithoutExt(String fileName)
    {
        if (StringUtils.isEmpty(fileName))
            return fileName;
        if (!fileName.contains("."))
            return fileName;
        return fileName.substring(0, fileName.lastIndexOf("."));
    }

    public static boolean fileExits(String fileName)
    {
        return new File(fileName).exists();
    }

    /**
     * 获取文件扩展名,不含有"."
     *
     * @param fileName
     * @return
     */
    public static String getExtendName(String fileName)
    {
        String ext = getNameExtend(fileName);
        if (StringUtil.isEmpty(ext))
            return fileName;
        return ext;
    }

    /**
     * 获取文件扩展名,含有"."
     *
     * @param fileName 文件名
     * @return 扩展名
     */
    public static String getNameExtend(String fileName)
    {
        if (fileName == null || fileName.equals(""))
        {
            return fileName;
        }
        int dot = fileName.lastIndexOf('.');
        if ((dot > -1) && (dot < (fileName.length() - 1)))
        {
            return fileName.substring(dot);
        }
        else
        {
            return null;
        }
    }

    /**
     * 检验是否为word文档
     *
     * @param fileName
     * @return
     */
    public static boolean checkWordDoc(String fileName)
    {
        if (fileName == null || fileName.equals(""))
        {
            return false;
        }
        String extendName = getExtendName(fileName);
        if (extendName == null || extendName.equals("")
                || (!extendName.equals("doc") && !extendName.equals("docx")))
        {
            return false;
        }
        return true;
    }

    public static boolean makeDir(File descFile)
    {
        if (!descFile.getParentFile().exists())
        {
            // 如果目标文件所在的目录不存在，则创建父目录
            if (!descFile.getParentFile().mkdirs())
                return false;
        }
        return true;
    }

    public static boolean forceDeleteFile(String filePath)
    {
        if (!deleteFile(filePath))
        {
            System.gc();
            return deleteFile(filePath);
        }
        return true;
    }

    public static boolean deleteFile(String filePath)
    {
        File file = new File(filePath);
        LOGGER.info("want to delete file:" + filePath);
        if (file.exists())
            return file.delete();
        return true;

    }

    public static String getChildPath(String realPath, String parentPath)
    {
        String rootPath = new File(realPath).getAbsolutePath();
        File parentFile = new File(parentPath);
        if (!parentFile.isDirectory())
            return null;
        String prefixPath = parentFile.getAbsolutePath();
        prefixPath = (prefixPath.endsWith(File.separator) ? prefixPath
                : prefixPath + File.separator);
        int index = rootPath.indexOf(prefixPath);
        if (index < 0)
            return null;
        return rootPath.substring(index + prefixPath.length());
    }

    public static List<String> readFileByLine(String fileName)
    {
        return readFileByLine(fileName, PropertiesUtil.getProperty(Constants.SpiderConfigKey
                .FILE_ENCODE));
    }

    /**
     * 按行读取文件
     *
     * @param fileName 文件名称
     * @return 行列表
     */
    public static List<String> readFileByLine(String fileName, String fileCode)
    {
        try
        {
            List<String> lineList = new ArrayList<String>();
            InputStreamReader ips = new InputStreamReader(new FileInputStream(new File(fileName))
                    , fileCode);
            BufferedReader file = new BufferedReader(ips);
            String str = null;
            while ((str = file.readLine()) != null)
                lineList.add(str);

            ips.close();
            file.close();

            return lineList;
        }
        catch (FileNotFoundException e)
        {
            throw new RuntimeException(e);
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args)
    {
        System.out.println(getExtendName("1.mp3"));
    }

    /**
     * 读取Excel文件
     *
     * @param file 文件
     * @return
     */
    public static List<Map<String, String>> getExcelContents(File file)
    {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        try
        {
            InputStream inputStream = new FileInputStream(file);
            Workbook wb = null;
            wb = new HSSFWorkbook(inputStream);
            Sheet sheet = wb.getSheetAt(0);
            int firstRowIndex = sheet.getFirstRowNum();
            int lastRowIndex = sheet.getLastRowNum();
            int sheetNum = sheet.getRow(0).getPhysicalNumberOfCells();
            for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++)
            {
                Row row = sheet.getRow(rIndex);
                if (row != null)
                {
                    int firstCellIndex = row.getFirstCellNum();
                    Map<String, String> map = new HashMap<String, String>();
                    for (int cIndex = firstCellIndex; cIndex < sheetNum; cIndex++)
                    {
                        Cell cell = row.getCell(cIndex);
                        String value = "";
                        if (cell != null)
                        {
                            value = cell.toString();
                            map.put("" + cIndex + "", value);
                        }
                    }
                    list.add(map);
                }
            }
        }
        catch (FileNotFoundException e)
        {
            throw new RuntimeException(e);
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
        return list;
    }


    public static String getFilePath(String fileName)
    {
        File file = new File(fileName);
        if (file.isDirectory())
            return file.getPath();
        return file.getParent();
    }

    /**
     * 下载文件
     *
     * @param destUrl 远程文件url
     * @param saveUrl 保存本地url
     */
    public static void saveToFile(String destUrl, String saveUrl)
    {
        File file = null;
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
        URL url = null;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;

        try
        {
            url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.setConnectTimeout(3000);
            httpUrl.setReadTimeout(3000);
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            file = new File(saveUrl);
            File file1 = new File(file.getPath().replace(file.getName(), ""));
            //判断当前是否目录
            if (!file1.exists())
            {
                file1.mkdirs();
            }
            fos = new FileOutputStream(file);
            while ((size = bis.read(buf)) != -1)
            {
                fos.write(buf, 0, size);
            }
            fos.flush();
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
        finally
        {
            try
            {
                fos.close();
                bis.close();
                httpUrl.disconnect();
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }
        }
    }
}
